package com.example.fall_guard_band.service;

import com.example.fall_guard_band.pojo.entity.RawSensorRecord;
import com.example.fall_guard_band.pojo.entity.SensorData;
import com.opencsv.CSVWriter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class CsvExportService {

    private static final String CSV_BASE_PATH = "src/main/resources/csv_log/";
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HHmm");
    private static final DateTimeFormatter TIMESTAMP_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 导出传感器数据到CSV文件
     * @param sensorData 传感器数据
     */
    public void exportSensorDataToCsv(SensorData sensorData) {
        try {
            // 解析frameTimestamp
            LocalDateTime frameTime = LocalDateTime.parse(sensorData.getFrameTimestamp(), TIMESTAMP_FORMATTER);
            
            // 创建目录结构
            String dateFolder = frameTime.format(DATE_FORMATTER);
            String csvFileName = frameTime.format(TIME_FORMATTER) + ".csv";
            
            File directory = createDirectoryIfNotExists(dateFolder);
            File csvFile = new File(directory, csvFileName);
            
            // 检查文件是否存在，如果存在则追加数据，否则创建新文件
            boolean fileExists = csvFile.exists();
            
            try (FileWriter fileWriter = new FileWriter(csvFile, true);
                 CSVWriter csvWriter = new CSVWriter(fileWriter)) {
                
                // 如果是新文件，写入表头
                if (!fileExists) {
                    writeHeader(csvWriter);
                }
                
                // 写入数据行
                writeDataRows(csvWriter, sensorData);
                
                log.info("传感器数据已成功导出到CSV文件: {}", csvFile.getAbsolutePath());
                
            }
            
        } catch (Exception e) {
            log.error("导出传感器数据到CSV文件失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 创建目录（如果不存在）
     */
    private File createDirectoryIfNotExists(String dateFolder) throws IOException {
        File baseDir = new File(CSV_BASE_PATH);
        File targetDir = new File(baseDir, dateFolder);
        
        if (!targetDir.exists()) {
            boolean created = targetDir.mkdirs();
            if (created) {
                log.info("创建CSV日志目录: {}", targetDir.getAbsolutePath());
            } else {
                throw new IOException("无法创建目录: " + targetDir.getAbsolutePath());
            }
        }
        
        return targetDir;
    }

    /**
     * 写入CSV表头
     */
    private void writeHeader(CSVWriter csvWriter) {
        String[] header = {
            "frame_timestamp",
            "device_id",
            "sensor_type",
            "sensor_timestamp",
            "x_value",
            "y_value", 
            "z_value",
            "magnitude"
        };
        csvWriter.writeNext(header);
    }

    /**
     * 写入数据行
     */
    private void writeDataRows(CSVWriter csvWriter, SensorData sensorData) {
        List<String[]> rows = new ArrayList<>();
        
        // 处理加速度计数据
        for (RawSensorRecord record : sensorData.getAccelerometerList()) {
            double magnitude = Math.sqrt(record.getX() * record.getX() + 
                                       record.getY() * record.getY() + 
                                       record.getZ() * record.getZ());
            
            String[] row = {
                sensorData.getFrameTimestamp(),
                sensorData.getDeviceId(),
                "accelerometer",
                record.getTimestamp(),
                String.valueOf(record.getX()),
                String.valueOf(record.getY()),
                String.valueOf(record.getZ()),
                String.valueOf(magnitude)
            };
            rows.add(row);
        }
        
        // 处理陀螺仪数据
        for (RawSensorRecord record : sensorData.getGyroscopeList()) {
            double magnitude = Math.sqrt(record.getX() * record.getX() + 
                                       record.getY() * record.getY() + 
                                       record.getZ() * record.getZ());
            
            String[] row = {
                sensorData.getFrameTimestamp(),
                sensorData.getDeviceId(),
                "gyroscope",
                record.getTimestamp(),
                String.valueOf(record.getX()),
                String.valueOf(record.getY()),
                String.valueOf(record.getZ()),
                String.valueOf(magnitude)
            };
            rows.add(row);
        }
        
        // 处理磁力计数据
        for (RawSensorRecord record : sensorData.getMagnetometerList()) {
            double magnitude = Math.sqrt(record.getX() * record.getX() + 
                                       record.getY() * record.getY() + 
                                       record.getZ() * record.getZ());
            
            String[] row = {
                sensorData.getFrameTimestamp(),
                sensorData.getDeviceId(),
                "magnetometer",
                record.getTimestamp(),
                String.valueOf(record.getX()),
                String.valueOf(record.getY()),
                String.valueOf(record.getZ()),
                String.valueOf(magnitude)
            };
            rows.add(row);
        }
        
        // 写入所有行
        csvWriter.writeAll(rows);
    }
}